package com.ygy.zhixin;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.*;
import android.os.Bundle;
import android.view.*;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;

//import com.example.android.apis.R;

public class ZhiXin extends GraphicsActivity
		implements ColorPickerDialog.OnColorChangedListener {

	private static final CharSequence[] ITEM = {"春意", "冬雪", "秋叶", "梦幻", "温馨", "可爱", "奔放"};
	private int width;
	private int height;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

//		Intent intent = new Intent(this, TTSplashActivity.class);
//		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//		this.startActivity(intent);

		setContentView(new MyView(this));


		WindowManager wm = this.getWindowManager();

		width = wm.getDefaultDisplay().getWidth();
		height = wm.getDefaultDisplay().getHeight();
		//mIsForeColor = false;
		mPainWidth = 2;

		mPaint = new Paint();
		mPaint.setAntiAlias(true);
		mPaint.setDither(true);
		mPaint.setColor(Color.BLUE);
		mPaint.setStyle(Paint.Style.STROKE);
		mPaint.setStrokeJoin(Paint.Join.ROUND);
		mPaint.setStrokeCap(Paint.Cap.ROUND);
		mPaint.setStrokeWidth(mPainWidth);

		//bkgPaint = new Paint();
		//bkgPaint.setColor(Color.rgb(200, 240, 240));

		pBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
		pCanvas = new Canvas(pBitmap);

		mBitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.bg5);
		mBitmap=zoomImage(mBitmap);

		currentBg = 5;

		bbb = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
		mCanvas = new Canvas(bbb);

		isSaved = false;
	}

	private Bitmap pBitmap;
	private Canvas pCanvas;
	private int currentBg;

	private boolean isSaved;

	private Paint       mPaint;
	//private Paint		bkgPaint;
	//private boolean		mIsForeColor;

	private Button		mButton1;
	private TextView	mTextView1;
	private int			mPainWidth;

	private int imgCnt;
	private String strCnt = null;

	public void colorChanged(int color) {

		mPaint.setColor(color);

	}
    
   /* public void flushCnt() {
    	
    	SharedPreferences set = getPreferences(Activity.MODE_PRIVATE);
    	strCnt = set.getString("s", "0");
    	SharedPreferences.Editor edt = set.edit();
    	int ii = Integer.parseInt(strCnt);
    	ii += 1;
    	edt.putString("s", ii+"");
    	edt.commit();
    }*/

	public void savePicture() {
		FileOutputStream fos = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		Date curDate = new Date(System.currentTimeMillis());
		String str = sdf.format(curDate);
		try {
			String strPath = new String("/sdcard/ZXImage/");
			File fPath = new File(strPath);
			if(!fPath.exists()) {
				fPath.mkdir();
			}

			File f = new File(strPath + "IMG" + str + ".jpg");
			if(!f.exists()) {
				try {
					f.createNewFile();
				}catch(IOException e) {
					e.printStackTrace();
				}
			}
			fos = new FileOutputStream(f);
			pBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
		}catch(FileNotFoundException e) {
			e.printStackTrace();
		}finally{
			if(fos!=null) {
				try {
					fos.flush();
					fos.close();
				}catch(IOException e) {
					e.printStackTrace();
				}
			}
		}
		File file = new File("/sdcard/ZXImage/IMG" + str + ".jpg");
		Toast.makeText(this,file.getAbsolutePath(),Toast.LENGTH_SHORT).show();
//		Intent mEIntent = new Intent(Intent.ACTION_SEND);
//		mEIntent.putExtra(Intent.EXTRA_EMAIL, "gyyang1987@gmail.com");
//		mEIntent.putExtra(Intent.EXTRA_CC, "gyyang1987@gmail.com");
//		mEIntent.putExtra(Intent.EXTRA_SUBJECT, "ZhiXin");
//		mEIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
//		mEIntent.setType("application/octet-stream");
//		this.startActivity(Intent.createChooser(mEIntent, "ZhiXin"));
	}

	private Canvas  mCanvas;
	private Bitmap  mBitmap;
	private Bitmap	bbb;

	////////////////////////Class MyView///////////////////////////
	public class MyView extends View {

		private static final float MINP = 0.25f;
		private static final float MAXP = 0.75f;

		private Path    mPath;
		private Paint   mBitmapPaint;



		public MyView(Context c) {
			super(c);
			mPath = new Path();
			mBitmapPaint = new Paint(Paint.DITHER_FLAG);
		}

		@Override
		protected void onSizeChanged(int w, int h, int oldw, int oldh) {
			super.onSizeChanged(w, h, oldw, oldh);
		}

		@Override
		protected void onDraw(Canvas canvas) {
			//canvas.drawColor(bkgPaint.getColor());

			canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
			canvas.drawBitmap(bbb, 0, 0, mBitmapPaint);

			canvas.drawPath(mPath, mPaint);
		}

		private float mX, mY;
		private static final float TOUCH_TOLERANCE = 4;

		private void touch_start(float x, float y) {
			mPath.reset();
			mPath.moveTo(x, y);
			mX = x;
			mY = y;
		}
		private void touch_move(float x, float y) {
			float dx = Math.abs(x - mX);
			float dy = Math.abs(y - mY);
			if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
				mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);
				mX = x;
				mY = y;
			}
		}
		private void touch_up() {
			mPath.lineTo(mX, mY);
			// commit the path to our offscreen
			mCanvas.drawPath(mPath, mPaint);
			//pCanvas.drawColor(bkgPaint.getColor());
			pCanvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
			pCanvas.drawBitmap(bbb, 0, 0, mBitmapPaint);
			pCanvas.save(Canvas.ALL_SAVE_FLAG);
			pCanvas.restore();

			// kill this so we don't double draw
			mPath.reset();
		}

		@Override
		public boolean onTouchEvent(MotionEvent event) {
			float x = event.getX();
			float y = event.getY();

			isSaved = false;

			switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
					touch_start(x, y);
					invalidate();
					break;
				case MotionEvent.ACTION_MOVE:
					touch_move(x, y);
					invalidate();
					break;
				case MotionEvent.ACTION_UP:
					touch_up();
					invalidate();
					break;
			}
			return true;
		}
	}

	private static final int FCOLOR_MENU_ID = Menu.FIRST;
	private static final int BCOLOR_MENU_ID = Menu.FIRST + 1;
	private static final int ERASE_MENU_ID = Menu.FIRST + 2;
	private static final int PWIDTH_MENU_ID = Menu.FIRST + 3;
	private static final int EXIT_MENU_ID = Menu.FIRST + 4;
	private static final int SAVE_MENU_ID = Menu.FIRST + 5;
	private static final int ABOUT_MENU_ID = Menu.FIRST + 6;
	private static final int NEW_MENU_ID = Menu.FIRST + 7;

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		getMenuInflater().inflate(R.menu.menu,menu);

//		menu.add(0, NEW_MENU_ID, 0, R.string.strNew).setIcon(android.R.drawable.ic_input_add);
//		menu.add(0, FCOLOR_MENU_ID, 0, R.string.fStrColor).setIcon(android.R.drawable.ic_menu_day);
//		menu.add(0, PWIDTH_MENU_ID, 0, R.string.strWidth).setIcon(android.R.drawable.ic_menu_crop);
//		menu.add(0, BCOLOR_MENU_ID, 0, R.string.bStrColor).setIcon(android.R.drawable.alert_light_frame);
//		menu.add(0, SAVE_MENU_ID, 0, R.string.strSave).setIcon(android.R.drawable.ic_menu_save);
//		menu.add(0, ERASE_MENU_ID, 0, R.string.strErase);
//		menu.add(0, ABOUT_MENU_ID, 0, R.string.strAbout);
//		menu.add(0, EXIT_MENU_ID, 0, R.string.strExit).setIcon(android.R.drawable.ic_menu_close_clear_cancel);

		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		super.onPrepareOptionsMenu(menu);
		return true;
	}

//	@Override
//	public boolean onOptionsItemSelected(MenuItem item) {
//		mPaint.setXfermode(null);
//		mPaint.setAlpha(0xFF);
//
//		switch (item.getItemId()) {
//			case NEW_MENU_ID:
//				//Toast.makeText(ZhiXin.this, "新建", Toast.LENGTH_SHORT).show();
//				//mCanvas.drawColor(bkgPaint.getColor());
//				//pCanvas.drawColor(bkgPaint.getColor());
//				if(!isSaved) {
//					isSavedDialog(false);
//				}else{
//					newView(true);
//				}
//				return true;
//			case FCOLOR_MENU_ID:
//				//mIsForeColor = true;
//				new ColorPickerDialog(this, this, mPaint.getColor()).show();
//				return true;
//			case BCOLOR_MENU_ID:
//				//mIsForeColor = false;
//				//new ColorPickerDialog(this, this, bkgPaint.getColor()).show();
//
//				AlertDialog dialog = new AlertDialog.Builder(ZhiXin.this)
//						.setTitle("背景设置")
//								//.setView(mView)
//						.setSingleChoiceItems(ITEM, currentBg-1, new DialogInterface.OnClickListener() {
//
//							@Override
//							public void onClick(DialogInterface dialog, int which) {
//								// TODO Auto-generated method stub
//								//Toast.makeText(ZhiXin.this, which + "", Toast.LENGTH_LONG).show();
//								currentBg = which + 1;
//								changBackGround();
//								dialog.dismiss();
//								newView(false);
//							}
//						}).create();
//
//				dialog.show();
//
//				return true;
//			case PWIDTH_MENU_ID:
//				LayoutInflater lf = LayoutInflater.from(ZhiXin.this);
//				final View mView = lf.inflate(R.layout.penwidth, null);
//				AlertDialog dPen = new AlertDialog.Builder(ZhiXin.this)
//						.setTitle("画笔宽度设置")
//						.setView(mView)
//						.setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//							@Override
//							public void onClick(DialogInterface dialog, int which) {
//								// TODO Auto-generated method stub
//								EditText et = (EditText)mView.findViewById(R.id.mEditTextPen);
//								String strPen = et.getText().toString();
//								strPen.trim();
//
//								if(strPen.length()!=0 && isInteger(strPen)) {
//									int intPen = Integer.parseInt(strPen);
//									if(intPen<1) {
//										mPainWidth = 1;
//									}else if(intPen>100) {
//										mPainWidth = 100;
//									}else{
//										mPainWidth = intPen;
//									}
//								}else{
//									mPainWidth = 1;
//								}
//								mPaint.setStrokeWidth(mPainWidth);
//							}
//						}).create();
//				dPen.show();
//				return true;
//			case ERASE_MENU_ID:
//				mPaint.setXfermode(new PorterDuffXfermode(
//						PorterDuff.Mode.CLEAR));
//				return true;
//			case SAVE_MENU_ID:
//				//flushCnt();
//				savePicture();
//				isSaved = true;
//				return true;
//			case ABOUT_MENU_ID:
//				LayoutInflater lfAbout = LayoutInflater.from(ZhiXin.this);
//				final View mViewAbout = lfAbout.inflate(R.layout.about, null);
//				AlertDialog dAbout = new AlertDialog.Builder(ZhiXin.this)
//						.setTitle(R.string.strAbout)
//						.setView(mViewAbout)
//						.create();
//				dAbout.show();
//				return true;
//			case EXIT_MENU_ID:
//				if(!isSaved) {
//					isSavedDialog(true);
//				}else{
//					finish();
//				}
//				return true;
//
//		}
//		return super.onOptionsItemSelected(item);
//	}


	public boolean onOptionsItemSelected(MenuItem item) {
		mPaint.setXfermode(null);
		mPaint.setAlpha(0xFF);

		switch (item.getItemId()) {
			case R.id.NEW_MENU_ID:
				//Toast.makeText(ZhiXin.this, "新建", Toast.LENGTH_SHORT).show();
				//mCanvas.drawColor(bkgPaint.getColor());
				//pCanvas.drawColor(bkgPaint.getColor());
				if(!isSaved) {
					isSavedDialog(false);
				}else{
					newView(true);
				}
				return true;
			case R.id.FCOLOR_MENU_ID:
				//mIsForeColor = true;
				new ColorPickerDialog(this, this, mPaint.getColor()).show();
				return true;
			case R.id.BCOLOR_MENU_ID:
				//mIsForeColor = false;
				//new ColorPickerDialog(this, this, bkgPaint.getColor()).show();

				AlertDialog dialog = new Builder(ZhiXin.this)
						.setTitle("背景设置")
								//.setView(mView)
						.setSingleChoiceItems(ITEM, currentBg-1, new OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								//Toast.makeText(ZhiXin.this, which + "", Toast.LENGTH_LONG).show();
								currentBg = which + 1;
								changBackGround();
								dialog.dismiss();
								newView(false);
							}
						}).create();

				dialog.show();

				return true;
			case R.id.PWIDTH_MENU_ID:
				LayoutInflater lf = LayoutInflater.from(ZhiXin.this);
				final View mView = lf.inflate(R.layout.penwidth, null);
				AlertDialog dPen = new Builder(ZhiXin.this)
						.setTitle("画笔宽度设置")
						.setView(mView)
						.setPositiveButton("确定", new OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								EditText et = (EditText)mView.findViewById(R.id.mEditTextPen);
								String strPen = et.getText().toString();
								strPen.trim();

								if(strPen.length()!=0 && isInteger(strPen)) {
									int intPen = Integer.parseInt(strPen);
									if(intPen<1) {
										mPainWidth = 1;
									}else if(intPen>100) {
										mPainWidth = 100;
									}else{
										mPainWidth = intPen;
									}
								}else{
									mPainWidth = 1;
								}
								mPaint.setStrokeWidth(mPainWidth);
							}
						}).create();
				dPen.show();
				return true;
			case R.id.ERASE_MENU_ID:
				mPaint.setXfermode(new PorterDuffXfermode(
						PorterDuff.Mode.CLEAR));
				return true;
			case R.id.SAVE_MENU_ID:
				//flushCnt();
				savePicture();
				isSaved = true;
				return true;
			case R.id.ABOUT_MENU_ID:
				LayoutInflater lfAbout = LayoutInflater.from(ZhiXin.this);
				final View mViewAbout = lfAbout.inflate(R.layout.about, null);
				AlertDialog dAbout = new Builder(ZhiXin.this)
						.setTitle(R.string.strAbout)
						.setView(mViewAbout)
						.create();
				dAbout.show();
				return true;
			case R.id.EXIT_MENU_ID:
				if(!isSaved) {
					isSavedDialog(true);
				}else{
					finish();
				}
				return true;

		}
		return super.onOptionsItemSelected(item);
	}

   /* public void startPainWidthActivity() {
    	Intent i = new Intent(ZhiXin.this, PainWidthActivity.class);
    	startActivityForResult(i, 0);
    }*/


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		Bundle b = data.getExtras();
		mPainWidth = b.getInt("painWidth");
		mPaint.setStrokeWidth(mPainWidth);
		//Toast.makeText(ZhiXin.this, mPainWidth + "", Toast.LENGTH_LONG).show();
	}

	public void changBackGround() {
		switch(currentBg) {
			case 1:
				mBitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.bg1);
				mBitmap=zoomImage(mBitmap);

				break;
			case 2:
				mBitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.bg2);
				mBitmap=zoomImage(mBitmap);
				break;
			case 3:
				mBitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.bg3);
				mBitmap=zoomImage(mBitmap);
				break;
			case 4:
				mBitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.bg4);
				break;
			case 5:
				mBitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.bg5);
				break;
			case 6:
				mBitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.bg6);
				break;
			case 7:
				mBitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.bg7);
				break;
			default:
				break;
		}
	}

	public void isSavedDialog(final boolean isExit) {
		AlertDialog nD = new Builder(ZhiXin.this)
				.setTitle("提示")
				.setMessage("要保存当前草稿吗？")
				.setPositiveButton("保存", new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						//flushCnt();
						savePicture();
						isSaved = true;

						if(isExit) {
							finish();
						}else{
							newView(true);
						}
					}
				})
				.setNegativeButton("不保存", new OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						if(isExit) {
							finish();
						}else{
							newView(true);
						}
					}
				}).create();
		nD.show();
	}



	public boolean isInteger(String s) {
		s = s.trim();
		try {
			Integer.parseInt(s);
			return true;
		}catch(NumberFormatException e) {
			return false;
		}
	}

	public void newView(boolean isNew) {
		if(isNew) {
			bbb = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
			mCanvas = new Canvas(bbb);
		}
		setContentView(new MyView(this));
	}


	public Bitmap zoomImage(Bitmap bgimage) {
		int bmpWidth=bgimage.getWidth();
		int bmpHeight=bgimage.getHeight();
        /* 设置图片放大的比例 */
//		float scale=1.25;
		float scale=(width/bmpWidth)>(height/bmpHeight)?width/bmpWidth:height/bmpHeight;
        /* 计算这次要放大的比例 */
		float scaleWidth =(float)(width/(float)bmpWidth);
		float scaleHeight=(float)(height/(float)bmpHeight);
        /* 产生reSize后的Bitmap对象 */
		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap resizeBmp = Bitmap.createBitmap(bgimage,0,0,bmpWidth,
				bmpHeight,matrix,true);


		return resizeBmp;
	}

}